﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using System.Linq;

public class GuideHuman : MonoBehaviour
{
    public HumanState humanState { get; private set; }
    private List<Vector3> nodes;
    private Animator animator;
    private float speed = 0.8f;
    private string aniID = "GuideHuman";
    // Use this for initialization
    void Start()
    {

    }

    private void OnDisable()
    {
        humanState = HumanState.Init;
    }

    public void Init(List<Vector3> nodeList)
    {
        if (animator == null)
        {
            animator = GetComponentInChildren<Animator>();
        }
        nodes = nodeList;
        transform.position = nodes[0];
        transform.DOPath(nodeList.ToArray(), GetTotalTime()).SetId(aniID).SetLookAt(0.01f);
        humanState = HumanState.Move;
        Pause();
    }

    private float GetTotalTime()
    {
        return TotalDistance() / speed;
    }

    private float TotalDistance()
    {
        float distance = 0;
        for (int i = 0; i < nodes.Count-1; i++)
        {
            distance += Vector3.Distance(nodes[i], nodes[i + 1]);
        }
        return distance;
    }

    public void Move()
    {
        if (humanState == HumanState.Move || humanState == HumanState.Init)
            return;
        humanState = HumanState.Move;
        DOTween.Play(aniID);
        SetAniState(AniName.Walk);
    }

    public void Pause()
    {
        if (humanState == HumanState.Pause || humanState == HumanState.Init)
            return;
        humanState = HumanState.Pause;
        DOTween.Pause(aniID);
        SetAniState(AniName.Idle);
    }

    private void SetAniState(AniName name)
    {
        ResetAniState();
        animator.SetBool(name.ToString(), true);
    }

    private void ResetAniState()
    {
        animator.SetBool(AniName.Walk.ToString(), false);
        animator.SetBool(AniName.Idle.ToString(), false);
    }
}

public enum AniName
{
    Walk,
    Idle
}

public enum HumanState
{
    Init,
    Move,
    Pause
}